//
//  Td.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/6/8.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

struct LiveSnData{
    var voiceChanger:Int     = 0
    var reverb:Int           = 0
    var isSysVolAuto:Bool    = true
    var audienceIds:[String] = []
}

struct AdcInfo {
    var userId:String?
    var isHandUp:Bool    = false
    var nickName:String  = "未知用户"
    var isLoading:Bool   = false
}

enum ReStreamType {
    case big
    case small
    case sub
}

struct UserInfo: Equatable {
    var userId:String?
    var isHandUp:Bool                    = false
    var isMute:Bool                      = false///远程默认关闭（因为关闭不触发回调），本地默认开启
    var isVdOpen:Bool                    = true
    var isAdc:Bool                       = false///暂时用不到
    var nickName:String                  = "未知用户"
    var streamType:ReStreamType          = .small
    
}

struct UserData {
    var remote:[UserInfo]   = []
    var local:[UserInfo]    = [UserInfo()]
    var adcs:[AdcInfo]      = []
    var max:Int             = 4
}

struct HandInfo {
    var userid:String?
    var name:String?
}

struct LiveData {
    var liveurl:String?
    var rtmpurl:String?
}

struct VideoEncoderParam {
    var videoResolution:String = "640x360"
    var resMode:Int = 0
    var videoFps:Int = 15
    var videoBitrate:Int = 1200
    var enableAdjustRes:Bool = false
}

struct VideoEncoderShareParam {
    var videoResolution:String = "1280x720"
    var resMode:Int = 0
    var videoFps:Int = 15
    var videoBitrate:Int = 1200
    var enableAdjustRes:Bool = false
    var hasSystomAudio:Bool = false
}


struct CloudData {
    /**
     设为焦点
     */
    var focusId:String             = mt_none

    /**
     查看视频
     */
    var lookId:String              = mt_none

    /**
     主持人id
     */
    var hostId:String              = mt_none

    /**
     会议人数
     */
    var meetingCount:Int           = 10

    /**
     会议时长
     */
    var meetingTime:Float         = 3600.0

    /**
     是否禁止屏幕共享
     */
    var disSd:Bool                = false

    /**
     是否禁止连麦
     */
    var disLink:Bool              = false

    /**
     是否禁止弹幕
     */
    var disBararage:Bool          = false

    /**
     是否全体静音状态
     */
    var isALLMute:Bool            = false

    /**
     是否全体视频开启状态
     */
    var isALLVdOpen:Bool          = true

    /**
     是否会议锁定状态
     */
    var isLock:Bool               = false

    /**
     是否开通直播
     */
    var hasLive:Bool             = false

    /**
     是否付费用户
     */
    var isVip:Bool               = false
    var days:Int                 = 0

    /**
     倒计时，初始值
     */
    var startTime:Double         = round(Date().timeIntervalSince1970).roundTo(places: 0)
    
    
    var isLeave:Bool             = false
    
    /**
     密码
     */
    var password:String          = ""
    var passwordCloud:String     = ""
}

//MARK: 参会sdk用到数据
struct TRTCPam {
    var sdkAppId:String      = kTencent_Live_api_id
    var userSig:String?
    var roomId:String?
    var role:TRTCRoleType    = .anchor
    var streamId:String?
    var userDefineRecordId:String?
    var privateMapKey:String?
    var bussInfo:String?
    
    var userId:String? {
        return UserInfoManager.shared.ownid
    }
}

enum TRTCScene {
    case meeting
    case live
}

struct ShareData {
    /**
    参会者是否开启并排模式
    */
    var param:VideoEncoderShareParam    = VideoEncoderShareParam()
    
    /**
     参会者是否开启并排模式
     */
    var hasSplit:Bool                   = false
    
    /**
     是否正在共享
     */
    var isSding:Bool                    = false
    var sdUserId:String?
}

struct ChatData {
    var userid:String?
    var isSender:Bool       = false
    var formName:String!
    var toNames:[String]    = []    //空的就是all
    var text:String!
    var time:String!
    var avator_Path:String?
    init(name:String,text:String) {
        self.formName = name
        self.text = text
        self.time = PE.timeNow()
    }
}

class Td :NSObject {
    private override init() {}
    private static var _sh:Td?
    class func sh() -> Td {
        guard let td = _sh else {
            _sh = Td()
            return _sh!
        }
        return td
    }
    
    class func destory() {
        self._sh = nil
    }
    
    lazy var lc: UserInfo = {
        var info:UserInfo?
        if Td.sh().usr.local[safe: 0] == nil {
            info = UserInfo.init()
        }else {
            info = Td.sh().usr.local[0]
        }
        info?.isMute = false//MTNot.getLocalMute()
        return info!
    }()
    
    class var fullScreen:Bool {
        return NSApplication.shared.currentSystemPresentationOptions == .fullScreen
    }
    
    class func isEnterRoom() -> Bool {
        let isok = Td.sh().usr.remote.count+Td.sh().usr.adcs.count != 0
        Td.sh().member = Td.sh().usr.adcs.count+Td.sh().usr.remote.count+1
        NotificationCenter.default.post(name: MTUserMemberNotification, object: Td.sh().member)
        return isok
    }
    
    /**
     场景(必填)
     */
    var scene:TRTCScene {
        return UserInfoManager.shared.scene==0 ? .meeting:.live
    }
    
    var name:String {
        return UserInfoManager.shared.name ?? mt_name_default
    }
    
    
    class var hands:[HandInfo] {
        let remote = Td.sh().usr.remote
        var list:[HandInfo] = []
        remote.forEach { (info) in
            if info.isHandUp == true {
                list.append(HandInfo.init(userid: info.userId, name: info.nickName))
            }
        }
        let adcs = Td.sh().usr.adcs
        adcs.forEach { (info) in
            if info.isHandUp == true {
                list.append(HandInfo.init(userid: info.userId, name: info.nickName))
            }
        }
        
        let local = Td.sh().lc
        if local.isHandUp {
            list.insert(HandInfo.init(userid: local.userId, name: local.nickName), at: 0)
        }
        return list
    }
    
    var member:Int           = 0
    var lastmessge:String    = ""
    
    /**
     是否参会者，或者主持人(必填)状态
     */
    var isJoin:Bool           = false

    /**
     腾讯入会基础数据（必填）
     */
    var params:TRTCPam        = TRTCPam()

    /**
     所有用户，静音等数据
     */
    var usr:UserData          = UserData()

    /**
     服务器保存的数据（必填）
     */
    var cloud:CloudData       = CloudData()

    /**
     只有直播模式用到的数据
     */
    var liveSn:LiveSnData     = LiveSnData()

    /**
     直播推流用到的数据
     */
    var live:LiveData         = LiveData()
    
    /**
     视频会议界面是否带有参会者列表状态
     */
    var hasUser:Bool          = false
    
    /**
     参会者列表是否独立弹出状态
     */
    var isStand:Bool          = false
    
    /**
     共享用到临时存取数据
     */
    var sd:ShareData          = ShareData()
    

    /**
    临时历史数据
    */
    var chats:[ChatData]      = [ChatData.init(name: "系统", text: "欢迎使用 ！👏")]
    
    /**
    视频分辨率帧率码率
    */
    var videoParam:VideoEncoderParam = VideoEncoderParam()
    
    
}



